import { useState, useEffect, useCallback, useRef } from 'react'

interface UseInfiniteScrollOptions {
  hasMore: boolean
  isLoading: boolean
  onLoadMore: () => void
  threshold?: number // 距离底部多少像素时触发加载
}

export function useInfiniteScroll({
  hasMore,
  isLoading,
  onLoadMore,
  threshold = 200
}: UseInfiniteScrollOptions) {
  const [isFetching, setIsFetching] = useState(false)
  const observerRef = useRef<IntersectionObserver | null>(null)
  const targetRef = useRef<HTMLDivElement | null>(null)

  // 处理加载更多
  const handleLoadMore = useCallback(async () => {
    if (isFetching || isLoading || !hasMore) return
    
    setIsFetching(true)
    try {
      await onLoadMore()
    } finally {
      setIsFetching(false)
    }
  }, [isFetching, isLoading, hasMore, onLoadMore])

  // 设置 Intersection Observer
  useEffect(() => {
    if (!targetRef.current) return

    const observer = new IntersectionObserver(
      (entries) => {
        const target = entries[0]
        if (target.isIntersecting && hasMore && !isLoading && !isFetching) {
          handleLoadMore()
        }
      },
      {
        rootMargin: `${threshold}px`,
        threshold: 0.1
      }
    )

    observer.observe(targetRef.current)
    observerRef.current = observer

    return () => {
      if (observerRef.current) {
        observerRef.current.disconnect()
      }
    }
  }, [hasMore, isLoading, isFetching, handleLoadMore, threshold])

  // 手动触发加载更多（用于按钮点击）
  const loadMore = useCallback(() => {
    handleLoadMore()
  }, [handleLoadMore])

  return {
    targetRef,
    isFetching: isFetching || isLoading,
    loadMore
  }
}